package com.cloud.gateway.task;

import com.cloud.gateway.bean.ReleaseInfo;
import com.cloud.gateway.core.ConfigLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class ReleaseVersionTask {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ConfigLoader configLoader;

    //5分钟执行一次
    @Scheduled(fixedRate = 300000)
    public void run() {
        log.info("ReleaseVersionTask running");

        //获取当前在线的版本
        Set<String> onlineVersions = new HashSet();
        List<String> services = discoveryClient.getServices();
        for (String serviceId : services) {
            List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
            for (ServiceInstance instance : instanceList) {
                String version = instance.getMetadata().get("version");
                if (StringUtils.isEmpty(version) || version.equals("undefined")) {
                    continue;
                }
                onlineVersions.add(version);
            }
        }

        //查找下线的版本
        Set<String> offlineVersions = new HashSet<>();
        List<ReleaseInfo> releaseInfoList = configLoader.getReleaseInfoList();
        for (ReleaseInfo releaseInfo : releaseInfoList) {
            String version = releaseInfo.getVersion();
            if (onlineVersions.contains(version)) {
                continue;
            }
            offlineVersions.add(version);
        }
        if (offlineVersions.size() > 0) {
            log.warn("offline version {}", offlineVersions.toString());
        }
    }

}
